
#include <string>
#include <iostream>
#include <cerrno>
#include <cstring>
#include <cstdlib>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <netdb.h>

int rsockfd;

void* readf(void*)
{
	char *host_name = (char*)"127.0.0.1";
	sockaddr_in serv_addr;
	int portno = 6565;
	rsockfd = ::socket(AF_INET, SOCK_STREAM, 0);

	if (rsockfd < 0) {
		std::cerr << "Error opening socket" << std::endl;
	}
	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
        inet_pton(AF_INET, host_name, &serv_addr.sin_addr);
	serv_addr.sin_port = htons(portno);

	if(::connect(rsockfd, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
		std::cerr << "ERROR connecting" << std::endl;
	}
	char buffer[255];
}
void* readff(void*)
{
	char buffer[255];
//	std::cout << "I will read in 20 seconds. My socket is ` " << sockfd << std::endl;
	std::cout << "Starting to read !" << std::endl;
      while(true){
		memset(buffer, 0, sizeof(buffer));
		int n = ::read(rsockfd, buffer, 255);
		if(n < 0) {
			std::cerr << "ERROR reading from socket" << std::endl;
		}
		std::cout << buffer << rsockfd << std::endl;
	}
}


int main()
{
	pthread_t p_read;
	pthread_t p_readf;
	pthread_create(&p_read, NULL, readf, NULL);
	sleep(5);
	pthread_create(&p_readf, NULL, readff, NULL);
	char buffer[255];
	while(true){
		std::cout <<"client sock"<< rsockfd << std::endl;
		memset(buffer,0,255);
		std::cout << "insert text to send" << std::endl;
		std::cin >> buffer;
		write(rsockfd, buffer, 255);}
	sleep(1000);
	return 0;
}
